package com.tomatozq.util;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.File;

public class Word2PDFConverter {
    private static final int wdFormatPDF = 17;// PDF 格式

    public static void convertByMSOffice(String wordFilePath,String pdfFilePath){
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", new Variant(false));
            Dispatch docs = app.getProperty("Documents").toDispatch();

            //转换前的文件路径
            String startFile = wordFilePath;

            //转换后的文件路劲
            String overFile =  pdfFilePath;

            doc = Dispatch.call(docs,  "Open" , startFile).toDispatch();

            File tofile = new File(overFile);

            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc,"SaveAs", overFile, wdFormatPDF);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            Dispatch.call(doc,"Close",false);
            if (app != null)
                app.invoke("Quit", new Variant[] {});
        }

        //结束后关闭进程
        ComThread.Release();
    }

    public static void convertByOpenOffice(String wordFilePath,String pdfFilePath){
        //soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
        File inputFile = new File(wordFilePath);
        File outputFile = new File(pdfFilePath);

        OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);

        try {
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(inputFile, outputFile);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try{ if(connection != null){connection.disconnect(); connection = null;}}catch(Exception e){}
        }
    }
}
